const Koa=require('koa');
const app=new Koa();

app.use(async ctx=>{
    if('GET'==ctx.method){
        ctx.body=`<form method=POST>
            username:<input type="text" name="username" value="Lily"><br>
            age:<input type="text" name="age" value="18"><br>
            email:<input type="text" name="email" value="aa@bb.com"><br>
            <input type="submit" value="Submit">
        </form>`;
    }else if('POST'==ctx.method){
        ctx.body=await parsePostData(ctx);
    }else{
        ctx.body='404!!';
    }
});

async function parsePostData(ctx) {
    return new Promise((resolve,reject)=>{
        try{
            let data='';
            ctx.req.addListener('data',chunk=>{
               data+=chunk;
            });
            ctx.req.addListener('end',()=>{
                resolve(parseQueryString(data));
            });
        }catch(err){
            reject(err);
        }
    });
}

function parseQueryString(qs) {
    console.log('qs:',qs);
    let data={},list=qs.split('&');
    list.forEach(item=>{
        let par=item.split('=');
        data[par[0]]=decodeURIComponent(par[1]);
    });
    return data;
}

app.listen(4000,()=>{
    console.log('Koa2 port:4000----'+new Date().toLocaleTimeString());
});